package com.dell.chen.servlet;

import com.dell.chen.dao.UserDao;
import com.dell.chen.dao.impl.UserDaoImpl;
import com.dell.chen.pojo.Users;
import com.dell.chen.service.Impl.UserServiceImpl;
import com.dell.chen.service.UserService;
import com.dell.chen.utils.WebUtils;
import com.google.gson.Gson;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：ChenwithIU
 * @date ：Created in 2020/11/24 18:45
 */
public class UserServlet extends BaseServlet{

    private UserService userService = new UserServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        Users login = userService.login(new Users(null, username, password, null, null, null, null, null, null));

        if (login == null ){//登录失败

            req.setAttribute("msg","用户名密码错误");
            req.setAttribute("username",username);

            //
            req.getRequestDispatcher("pages/Floda/login.jsp").forward(req,resp);

        }else {
            // 登录 成功
            // 保存用户登录的信息到Session域中
            req.getSession().setAttribute("user", login);
            //跳到成功页面首页
            req.getRequestDispatcher("index.jsp").forward(req,resp);
        }

    }

    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");

//        Users users = WebUtils.copyParamToBean(req.getParameterMap(), new Users());

        if (userService.existUsername(username)){
            System.out.println("用户名[" + username + "]已存在!");

            //回显信息，保存到Request域中
            req.setAttribute("msg","用户名已存在！");
            req.setAttribute("username",username);
            req.setAttribute("phone",phone);

            //注册失败  跳回login.jsp
            req.getRequestDispatcher("pages/Floda/index.jsp").forward(req,resp);

        }else {
            //注册。加入到数据库
            userService.register(new Users(null,username,password,name,null,null,phone,null,null));

            //跳回首页
            req.getRequestDispatcher("pages/Floda/register_success.jsp").forward(req,resp);
        }
    }

    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的参数
        String username = req.getParameter("username");

        //调用userService.existsUsername();
        boolean existsUsername = userService.existUsername(username);

        //把返回的结果封装成为map对象
        Map<String,Object> resultMap= new HashMap<>();

        resultMap.put("existUsername",existsUsername);

        Gson gson = new Gson();

        String json = gson.toJson(resultMap);

        resp.getWriter().write(json);


    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {



        //封装数据
        Users users = WebUtils.copyParamToBean(req.getParameterMap(), new Users());

        //调用update
        userService.update(users);

        String username = users.getUsername();

        req.getSession().invalidate();

        String password = users.getPassword();

        Users login = userService.login(new Users(null, username, password, null, null, null, null, null, null));


        req.getSession().setAttribute("user",login);

        //转发
//        req.getRequestDispatcher(req.getContextPath() + "/userServlet?action=update&username="+username).forward(req,resp);

        req.getRequestDispatcher("pages/Floda/message.jsp").forward(req,resp);
    }



    protected void upLoad(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //  1、获取请求的参数
        int id = 0;
        String username = null;
        String name = null;
        int age = 0;
        String gender = null;
        String phone = null;
        String password = null;
        String changePassword =null;
        String img_path = null;
        String address = null;

        //1.先判断上传的数据是否是多段数据(只有是多段的数据才是文件上传)
        if (ServletFileUpload.isMultipartContent(req)){
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析的上传数据的工具类ServletFileUpload类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            //解析上传的数据，得到每一个表单项FileItem
            try {
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //循环判断，每一个表单项，是普通类型，还是上传的文件
                for (FileItem fileItem:list) {
                    if (fileItem.isFormField()){
                        //普通表单项
                        if ("name".equals(fileItem.getFieldName())){
                            System.out.println("姓名："+fileItem.getString("UTF-8"));
                            name = fileItem.getString("UTF-8");
                        } else if ("age".equals(fileItem.getFieldName())){
                            if (fileItem.getString("UTF-8")==null){
                                System.out.println("年龄：0");
                                age = 0;
                            }else{
                                System.out.println("年龄："+fileItem.getString("UTF-8"));
                                age = Integer.parseInt(fileItem.getString("UTF-8"));
                            }
                        }
                        else if ("id".equals(fileItem.getFieldName())){
                            System.out.println("id："+fileItem.getString("UTF-8"));
                            id = Integer.parseInt(fileItem.getString("UTF-8"));
                        }
                        else if ("username".equals(fileItem.getFieldName())){
                            System.out.println("用户名："+fileItem.getString("UTF-8"));
                            username = fileItem.getString("UTF-8");
                        }
                        else if ("gender".equals(fileItem.getFieldName())){
                            System.out.println("性别："+fileItem.getString("UTF-8"));
                            gender = fileItem.getString("UTF-8");
                        }
                        else if ("address".equals(fileItem.getFieldName())){
                            System.out.println("收货地址："+fileItem.getString("UTF-8"));
                            address = fileItem.getString("UTF-8");
                        }
                        else if ("phone".equals(fileItem.getFieldName())){
                            System.out.println("联系方式："+fileItem.getString("UTF-8"));
                            phone = fileItem.getString("UTF-8");
                        }else if ("password".equals(fileItem.getFieldName())){
                            System.out.println("密码："+fileItem.getString("UTF-8"));
                            password = fileItem.getString("UTF-8");
                        }

                    }else {
                        //上传文件
                        System.out.println("上传照片："+fileItem.getName());
                        img_path = "tx/"+fileItem.getName();
                        fileItem.write(new File("E:\\桌面\\Flower\\out\\artifacts\\Flower_war_exploded\\tx\\"+fileItem.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }




                Users user=new Users(id, username, password, name, gender, age, phone, address, img_path);
//            lostService.addLost(new Lost(null,null,phone,address,email,petsname,varieties,petsphoto,petsage,lostintroduce,time));
                userService.update(user);
                req.getSession().setAttribute("user",user);
                req.getRequestDispatcher("/pages/Floda/message.jsp").forward(req, resp);

        }
    }



}
